// index.js
// 获取应用实例
import {
  post,
  put
} from '../../utils/request'
import {
  APIS
} from '../../utils/api'
const app = getApp();

Page({
  data: {
    operateList: [{
      text: '我的订单',
      url: '/pages/order/index',
      isRoot: true
    },
    {
      text: '门店优惠',
      url: '/subPackage/pages/coupon',
      isRoot: false
    },
    {
      text: '加入我们',
      url: '',
      isRoot: false
    },
    {
      text: '操作指南',
      url: '',
      isRoot: false
    }
    ],
    userInfo: {},
    bannerList: [],
    avatarUrl: '',
    showNameUpdate: false,
  },
  onLoad() {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo
    });
    if (userInfo.id) {
      this.getBannerList();
    }
  },
  handleUpdateName() {
    this.setData({
      showNameUpdate: true
    });
  },
  getBannerList() {
    post(APIS.banner, { type: 2 }).then(res => {
      const list = res.data;
      this.setData({
        bannerList: list.map(x => x.img)
      });
    })
  },
  handleJumpToPay() {
    wx.navigateTo({
      url: '/subPackage/pages/pay'
    })
  },
  handleJump(e) {
    const {
      item
    } = e.target.dataset;
    if (!item.url) {
      return
    }
    if (item.isRoot) {
      wx.switchTab({
        url: item.url
      })
    } else {
      wx.navigateTo({
        url: item.url
      })
    }
  },
  handleJumpToPay() {
    wx.navigateTo({
      url: '/subPackage/pages/pay'
    })
  },
  updateUser(params) {
    const id = this.data.userInfo.id;
    put(`${APIS.user}/${id}`, params).then(res => {
      if(res.code === 0) {
        wx.setStorageSync('userInfo', res.data);
        this.setData({
          userInfo: res.data
        });
      }
      else {
        wx.setStorageSync('userInfo', {});
      }
    })
  },
  handleInput(e) {
    const { value } = e.detail;
    this.setData({
      currentUpdateName: value
    })
  },
  handleConfimName(e) {
    const { value } = e.detail;
    this.updateUser({ username: value });
  },
  handleConfimNickname(e) {
    const { pass } = e.detail;
    if (pass) {
      this.updateUser({ username: this.data.currentUpdateName });
    }
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    console.log(1212, avatarUrl);
    // wx.uploadFile({
    //   url: APIS.upload,12, 
    //   filePath: tempFilePaths[0],
    //   name: 'file',
    //   success(res) {
    //     try {
    //       const data = res.data;
    //       const info = data && JSON.parse(data);
    //       const { file } = info.data;
    //       that.setData({
    //         currentImg: file
    //       });
    //     } catch (error) {
          
    //     }
    //   }
    // })
    this.setData({
      avatarUrl,
    });
    this.updateUser({ avatar: avatarUrl });
  },
  onShareAppMessage() {
    return getApp().globalData.shareMessage
  }
})